"use strict";

var _typeof =
  typeof Symbol === "function" && typeof Symbol.iterator === "symbol"
    ? function(obj) {
        return typeof obj;
      }
    : function(obj) {
        return obj &&
        typeof Symbol === "function" &&
        obj.constructor === Symbol &&
        obj !== Symbol.prototype
          ? "symbol"
          : typeof obj;
      };

$(document).ready(function() {
  if ($("x-guanlian .main_table").css("display") === "none") {
    $("#add_new_guanlian_table").one("click", function(evt) {
      $("x-guanlian .placeholder").remove();
      $("x-guanlian .main_table").css("display", "block");
    });
  } else {
    $("#add_new_guanlian_table").remove();
  }

  // 添加关联 按钮
  $("#add_new_guanlian").on({ click: addNewGuanlian }, {});
  $("x-guanlian .btn_modifiy").each(function(index, item) {
    $(item).on({ click: modifyThisLine }, {});
  });
  // 转义关联理由
  // $('x-guanlian ul .line_4:not(:first)').each((index, item) => {
  //   $(item).text(unescape($(item).text()))
  // })
});
var gID = location.href.match(/\/id\/(\d+)/)[1];
if (Number(gID) === Infinity) {
  throw new Error(
    "\u83B7\u53D6\u4EA7\u54C1id\u5931\u8D25\uFF0Cid\u503C\u4E3A" + gID
  );
}
var templ = "\n  <div style='width:100%;margin:0 auto;text-align:center;'>\n    <select name=\"choseDalei\" id=\"popup_choseDalei\" form='not_submit'\n    style='margin: 0 auto;width: 35rem;height: 2.5rem;line-height: 2.5rem;display: block;margin-top:1rem;'>\n      <option value=\"false\">\u8BF7\u7B49\u5F85\u7F51\u7EDC\u52A0\u8F7D</option>\n    </select>\n    <select name=\"choseXiaolei\" id=\"popup_choseXiaolei\" form='not_submit'\n    style='margin: 0 auto;width: 35rem;height: 2.5rem;line-height: 2.5rem;display: block;margin-top:1rem;'>\n      <option value=\"false\">\u8BF7\u9009\u62E9\u5927\u7C7B</option>\n    </select>\n    <div style='margin: 0 auto;width: 35rem;line-height: 2.5rem;display: block;margin-top:1rem;'>\n      <select name=\"choseXiaoming\" id=\"popup_choseXiaoming\" form='not_submit' style='width:100%;'>\n        <option value=\"false\">\u8BF7\u9009\u62E9\u5C0F\u7C7B</option>\n      </select>\n    </div>\n  </div>\n  <div id='popup_confirm' style='display:none;width:7rem;margin:auto;background:#007cb8;color:#fff;text-align: center;margin-top: 1rem;line-height: 2.5rem;cursor: pointer;'>\u786E\u8BA4\u63D0\u4EA4</div>\n".trim();
function addNewGuanlian(evt) {
  var frameID = layer.open({
    type: 1,
    area: ["700px", "450px"],
    title: "选择关联产品",
    shadeClose: true,
    content: "" + templ
  });
  if (
    String(
      typeof frameID === "undefined" ? "undefined" : _typeof(frameID)
    ).toLowerCase() === "number" &&
    frameID > 0
  ) {
    var optionListDalei = "";
    $.ajax(String($("#post_ajax_get_dalei").val()), {
      method: "post",
      data: { data: "test" }
    })
      .fail(function(err) {
        alert(
          "\u7F51\u7EDC\u8FDE\u63A5\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC"
        );
        throw err;
      })
      .done(function(data) {
        if (String(data.code) === "1") {
          $.each(data.data, function(index, item) {
            optionListDalei +=
              '<option value="' + item.id + '">' + item.name + "</option>";
          });
        } else {
          alert(
            "\u670D\u52A1\u5668\u54CD\u5E94\u9519\u8BEF\uFF0C\u8FD4\u56DE\uFF1A" +
              data.message
          );
          throw new Error(
            "\u670D\u52A1\u5668\u54CD\u5E94\u9519\u8BEF\uFF0C\u8FD4\u56DE\uFF1A" +
              data.message
          );
        }
      })
      .done(function(data) {
        console.log(optionListDalei);
        $("#popup_choseDalei")
          .empty()
          .append(optionListDalei);
        $("#popup_choseDalei").val(null);
      });
    $("#popup_choseDalei").on("change", function(evt) {
      $("#popup_choseXiaolei").val(null);
      $("#popup_choseXiaolei")
        .empty()
        .append(
          '<option value="false">\u6B63\u5728\u52A0\u8F7D\u8BF7\u7A0D\u5019</option>'
        );
      $("#popup_choseXiaoming").val(null);
      $("#popup_choseXiaoming")
        .empty()
        .append(
          '<option value="false">\u8BF7\u9009\u62E9\u5C0F\u7C7B</option>'
        );
      var xiaoleiOptionList = Promise.resolve($(evt.target).val());
      xiaoleiOptionList
        .then(function(value) {
          return Getxiaolei(value);
        })
        .then(function(value) {
          console.log(value);
          $("#popup_choseXiaolei")
            .empty()
            .append(String(value));
          $("#popup_choseXiaolei").val(null);
        });
    });
    $("#popup_choseXiaolei").on("change", function(evt) {
      $("#popup_choseXiaoming").val(null);
      $("#popup_choseXiaoming")
        .empty()
        .append(
          '<option value="false">\u6B63\u5728\u52A0\u8F7D\u8BF7\u7A0D\u5019</option>'
        );
      var xiaomingOptionList = Promise.resolve($(evt.target).val());
      xiaomingOptionList
        .then(function(value) {
          return Getxiaoming(value);
        })
        .then(function(value) {
          console.log(value);
          $("#popup_choseXiaoming option").remove();
          $("#popup_choseXiaoming")
            .select2({
              data: value
            })
            .val(null)
            .trigger("change");
        });
    });
    $("#popup_choseXiaoming").on("change", function(evt) {
      if (
        $("#popup_choseXiaoming").val() !== null &&
        $("#popup_choseXiaoming").val() !== "" &&
        $("#popup_choseXiaoming").val().length > 0
      ) {
        $("#popup_confirm").css("display", "block");
        $("#popup_confirm").off("click");
        $("#popup_confirm").one({ click: writeBackGuanlian }, {});
      } else {
        $("#popup_confirm").off("click");
        $("#popup_confirm").css("display", "none");
      }
    });
    // 新建多选下拉框
    $("#popup_choseXiaoming")
      .select2({
        placeholder: "请选择小名",
        tags: false,
        multiple: true,
        minimumResultsForSearch: Infinity,
        width: "element",
        closeOnSelect: false
      })
      .val(null)
      .trigger("change");
  }
}
function Getxiaolei(fID) {
  var optionList = "";
  return new Promise(function(resolve, reject) {
    $.ajax(String($("#post_ajax_get_cpclass").val()), {
      method: "post",
      data: { f_id: fID }
    })
      .fail(function(err) {
        alert(
          "\u83B7\u53D6\u5C0F\u7C7B\u5217\u8868\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC"
        );
        $("#popup_choseDalei").val("");
        reject(err);
        throw err;
      })
      .done(function(data) {
        if (String(data.code) === "1") {
          $.each(data.data, function(index, item) {
            optionList +=
              '<option value="' + item.id + '">' + item.name + "</option>";
          });
          console.log(optionList);
          resolve(optionList);
        } else {
          alert(
            "\u670D\u52A1\u5668\u54CD\u5E94\u5F02\u5E38\uFF1A" + data.message
          );
          reject(
            new Error(
              "\u670D\u52A1\u5668\u54CD\u5E94\u5F02\u5E38\uFF1A" + data.message
            )
          );
          throw new Error(
            "\u670D\u52A1\u5668\u54CD\u5E94\u5F02\u5E38\uFF1A" + data.message
          );
        }
      });
  });
}
function Getxiaoming(cpTemp) {
  var optionList = "";
  return new Promise(function(resolve, reject) {
    $.ajax(String($("#post_ajax_get_litter_name").val()), {
      method: "post",
      data: { cp_temp: cpTemp }
    })
      .fail(function(err) {
        alert(
          "\u83B7\u53D6\u5C0F\u540D\u5217\u8868\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC"
        );
        $("#popup_choseXiaolei").val(null);
        reject(err);
        throw err;
      })
      .done(function(data) {
        if (String(data.code) === "1") {
          var dataSource = [];
          $.each(data.data, function(index, item) {
            dataSource.push({
              id: item.id,
              text: item.litter_name
            });
          });
          console.log(dataSource);
          resolve(dataSource);
        } else {
          alert(
            "\u670D\u52A1\u5668\u54CD\u5E94\u5F02\u5E38\uFF1A" + data.message
          );
          reject(
            new Error(
              "\u670D\u52A1\u5668\u54CD\u5E94\u5F02\u5E38\uFF1A" + data.message
            )
          );
          throw new Error(
            "\u670D\u52A1\u5668\u54CD\u5E94\u5F02\u5E38\uFF1A" + data.message
          );
        }
      });
  });
}

function modifyThisLine(evt) {
  var value = $(evt.target)
    .closest("ul")
    .find(".line_4")
    .text();
  var heightValue = $(evt.target)
    .closest("ul")
    .find(".line_4")
    .height();
  $(evt.target)
    .closest("ul")
    .find(".line_4")
    .height(heightValue);
  $(evt.target)
    .closest("ul")
    .find(".line_4")
    .text(null)
    .append(
      "<textarea title='\u70B9\u51FB\u7A7A\u767D\u5904\u4FDD\u5B58' style='height:100%;width:100%;'></textarea>"
    );
  $(evt.target)
    .closest("ul")
    .find(".line_4 textarea")
    .focus()
    .val(value);
  $(evt.target)
    .closest("ul")
    .find(".line_4 textarea")
    .on("blur", function(evt) {
      var text = String($(evt.target).val());
      $(evt.target)
        .closest("ul")
        .find(".line_4")
        .text(text);
    });
}

function writeBackGuanlian(evt) {
  var formValue = {
    daleiid: $("#popup_choseDalei").val(),
    cp_class: $("#popup_choseXiaolei").val(),
    /* 关联理由 */
    link_reason: "",
    /* 关联所属产品 */
    g_id: gID,
    /* 被关联产品 */
    link_g_id: $("#popup_choseXiaoming").val()
  };
  var formTextValue = {
    dalei: $(
      "#popup_choseDalei option[value='" + $("#popup_choseDalei").val() + "']"
    ).text(),
    xiaolei: $(
      "#popup_choseXiaolei option[value='" +
        $("#popup_choseXiaolei").val() +
        "']"
    ).text(),
    // 去重的时候添加
    xiaoming: []
  };
  var uniformValue = {
    daleiid: formValue.daleiid,
    cp_class: formValue.cp_class,
    /* 关联理由 */
    link_reason: formValue.link_reason,
    /* 关联所属产品 */
    g_id: formValue.g_id,
    /* 被关联产品 */
    link_g_id: []
  };
  var hadValue = [""];
  // 构建已有值
  $("x-guanlian .line_3").each(function(index, item) {
    if (index === 0) {
      // 表头
    } else if (index === 1) {
      hadValue = [String($(item).attr("inori-data-id"))];
    } else {
      hadValue.push(String($(item).attr("inori-data-id")));
    }
  });
  if (typeof formValue.link_g_id === "string") {
    formValue.link_g_id = ["" + formValue.link_g_id];
  }
  // 比对检验是否重复添加
  $.each(formValue.link_g_id, function(index, item) {
    if (hadValue.indexOf(item) === -1) {
      uniformValue.link_g_id.push(item);
      formTextValue.xiaoming.push(
        $("#popup_choseXiaoming option[value='" + item + "']").text()
      );
    }
  });
  // 去重后数组不为空的时候，post到服务器并在成功后append列表
  if (uniformValue.link_g_id.length > 0) {
    var newGuanlian = "";
    alert(
      "\u6B63\u5728\u8BF7\u6C42\u6570\u636E\u5199\u5165\u6743\u9650\uFF0C\u8BF7\u7A0D\u540E\u3002"
    );
    Promise.resolve(uniformValue)
      .then(function(postData) {
        var promiseQuery = [];
        $.each(postData.link_g_id, function(index, item) {
          var postDataItem = Object.assign({}, postData);
          postDataItem.link_g_id = postDataItem.link_g_id[index];
          promiseQuery.push(ajaxPostGuanlianArray(postDataItem));
        });
        return Promise.all(promiseQuery);
      })
      .then(function(rawValue) {
        // if (typeof rawValue.phpValue === 'string') {
        //   rawValue.phpValue = [rawValue.phpValue]
        // }
        uniformValue.link_g_id = String(uniformValue.link_g_id).split(",");
        $.each(rawValue, function(index, item) {
          newGuanlian += ('\n        <ul>\n          <li class="line_1" inori-data-id=\'' +
            uniformValue.daleiid +
            "'>" +
            formTextValue.dalei +
            '</li>\n          <li class="line_2" inori-data-id=\'' +
            uniformValue.cp_class +
            "'>" +
            formTextValue.xiaolei +
            '</li>\n          <li class="line_3" inori-data-id=\'' +
            uniformValue.link_g_id[index] +
            "'>" +
            formTextValue.xiaoming[index] +
            '</li>\n          <li class="line_4" style=\'min-height:4rem;\'>\u5173\u8054\u7406\u7531</li>\n          <li class="line_5"><div class="btn btn_modifiy" style="background-image:url(\'' +
            $("x-guanlian").attr("btn-img-url") +
            "');\">\u4FEE\u6539\u5173\u8054\u7406\u7531</div></li>\n          <li class=\"line_6\"><div class=\"btn btn_del\" onclick='deleThisGuanlianLine(this, event)'>\u5220\u9664</div></li>\n          <input type='hidden' class='lineGuanlianID' value='" +
            item.phpValue +
            "'>\n        </ul>\n        ").trim();
        });
        $(".main_table").append(newGuanlian);
        layer.closeAll();
        // 重新挂一次事件
        $("x-guanlian .btn_modifiy").each(function(index, item) {
          $(item).off("click");
          $(item).on({ click: modifyThisLine }, {});
        });
      });
  } else {
    alert("您选择添加的关联产品都已存在，请检查列表");
    $("#popup_choseDalei").val(null);
    $("#popup_confirm").one({ click: writeBackGuanlian }, {});
    throw new Error("关联产品全部重复");
  }
}
function ajaxPostGuanlianArray(data) {
  var postURL = String($("#post_ajax_add_goods_links").val());
  // data.link_g_id = data.link_g_id.join(',')
  return new Promise(function(resolve, reject) {
    $.ajax(postURL, {
      method: "post",
      data: data
    })
      .done(function(res) {
        if (String(res.code) === "1") {
          resolve({
            formData: data,
            phpValue: res.goods_link_id
          });
        } else {
          reject(
            new Error(
              "\u670D\u52A1\u5668\u54CD\u5E94\u9519\u8BEF\uFF1A " + data.message
            )
          );
        }
      })
      .fail(function(err) {
        $("#popup_confirm").one({ click: writeBackGuanlian }, {});
        reject(err);
      });
  });
}

function deleThisGuanlianLine(_this, event) {
  var ID = $(_this)
    .closest("ul")
    .find(".lineGuanlianID")
    .val();
  var AjaxURL = String($("#post_ajax_del_goods_links").val());
  $.ajax(AjaxURL, {
    method: "post",
    data: { goods_link_id: ID },
    beforeSend: function beforeSend() {
      layer.msg("\u6B63\u5728\u4E0E\u670D\u52A1\u5668\u901A\u4FE1");
    }
  })
    .done(function(data) {
      if (String(data.code) === "1") {
        layer.closeAll();
        $(_this)
          .closest("ul")
          .remove();
      } else {
        alert(
          "\u670D\u52A1\u5668\u54CD\u5E94\u5F02\u5E38\uFF1A" + data.message
        );
        throw new Error(
          "\u670D\u52A1\u5668\u54CD\u5E94\u5F02\u5E38\uFF1A" + data.message
        );
      }
    })
    .fail(function(err) {
      console.log(err);
      throw err;
    });
}

function submitGuanlian() {
  // const dalei = Array.from($('x-guanlian ul .line_1:not(:first)').map((index, item) => { return $(item).attr('inori-data-id') })).join(',')
  // const xiaolei = Array.from($('x-guanlian ul .line_2:not(:first)').map((index, item) => { return $(item).attr('inori-data-id') })).join(',')
  var xiaoming = Array.from(
    $("x-guanlian ul .line_3:not(:first)").map(function(index, item) {
      return $(item).attr("inori-data-id");
    })
  ).join(",");
  /* 防止出现逗号妨碍分割，为此需要在显示时手动unescape一次 */
  // const guanlianReason = Array.from($('x-guanlian ul .line_4:not(:first)').map((index, item) => { return escape($(item).text()).toLocaleLowerCase() })).join(',')
  // const guanlianID = Array.from($('x-guanlian ul .lineGuanlianID').map((index, item) => { return $(item).val() })).join(',')
  var formValueArray = [];
  $("x-guanlian ul:not(:first)").each(function(index, item) {
    formValueArray.push({
      goods_link_id: $(item)
        .find(".lineGuanlianID")
        .val(),
      link_reason: $(item)
        .find(".line_4")
        .text()
    });
  });
  $.ajax(String($("#post_ajax_update_goods_links").val()), {
    method: "post",
    data: { data: formValueArray },
    beforeSend: function beforeSend() {
      layer.msg("正在发送关联表格数据", {
        icon: 16,
        shade: 0.01
      });
    }
  })
    .fail(function(err) {
      layer.msg(
        "\u53D1\u9001\u5173\u8054\u8868\u683C\u6570\u636E\u5931\u8D25\uFF01\u8BF7\u91CD\u8BD5"
      );
      throw err;
    })
    .done(function(res) {
      layer.closeAll();
      var encodeRes = res;
      /* 服务器返回修改数组，0为未修改，1 为修改成功 */
      var flag = true;
      $.each(encodeRes.data, function(index, item) {
        if (item !== 1 && item !== 0) {
          flag = false;
        }
      });
      if (flag) {
      } else {
        alert(
          "\u670D\u52A1\u5668\u54CD\u5E94\u5F02\u5E38\uFF1A " + encodeRes.data
        );
        throw new Error(
          "\u670D\u52A1\u5668\u54CD\u5E94\u5F02\u5E38\uFF1A " + encodeRes.data
        );
      }
    });
}
